<template>
  <div class="quotation layout-main">
    <a-spin :spinning="loading">
      <a-alert
        :show-icon="false"
        class="closingDate"
        :message="`截止时间：${$getTime(quotationData.expirationDate)}`"
        banner
      />
      <div class="content flex">
        <div class="content_l">
          <div class="content_l_head flex flex-align-c">
            <div class="status tc">
              <TagsDetailStatus
                :flag="checkedQuotationProduct.quotationDetailSalesState"
              />
            </div>
            <div class="goods">
              <span>{{ quotationData.categoryName }}</span>
              <a-divider type="vertical" />
              <span>{{ checkedQuotationProduct.brand }} </span>
              <span>{{ checkedQuotationProduct.spec }} </span>
              <span>{{ checkedQuotationProduct.material }} </span>
            </div>
          </div>
          <div class="goodsData flex">
            <div class="goodsData_l">
              <c-desc :column="1" :columns="goodsDescCols">
                <template v-slot:price>
                  <i
                    class="flag fs-16 bold"
                    :class="[
                      quotationData.priceType ===
                      quotationDict.priceType.pricing.value
                        ? pricingPriceChange(quotationData.futuresContract)
                        : 'danger'
                    ]"
                    >￥</i
                  >
                  <template
                    v-if="
                      quotationData.priceType ===
                        quotationDict.priceType.pricing.value
                    "
                  >
                    <span
                      class="fs-26 bold"
                      :class="[
                        pricingPriceChange(quotationData.futuresContract)
                      ]"
                      >{{
                        getPricingPrice(
                          quotationData.futuresContract,
                          checkedQuotationProduct.premium
                        )
                      }}
                    </span>
                    <span
                      >( {{ quotationData.futuresContract }}
                      <i v-if="checkedQuotationProduct.premium >= 0">+</i
                      >{{ checkedQuotationProduct.premium }} )</span
                    >
                  </template>
                  <template v-else>
                    <span class="fs-26 danger bold"
                      >{{ checkedQuotationProduct.price }}
                    </span>
                    <i class="fs-14">元/吨</i>
                  </template>
                </template>
                <template v-slot:amount>
                  <span class="weight"
                    >{{ checkedQuotationProduct.amountAvailable }}
                  </span>
                  <i class="fs-14">吨</i>
                </template>
              </c-desc>
            </div>
            <div
              class="goodsData_r"
              v-if="
                quotationData.priceType ===
                  quotationDict.priceType.pricing.value
              "
            >
              <div class="title">
                合约盘面数据
              </div>
              <ul class="market">
                <div class="flex-between">
                  <li>
                    <span class="label">最新价</span>
                    <span class="text">{{
                      parseInt(futureData && futureData.lastPrice) || ""
                    }}</span>
                  </li>
                  <li>
                    <span class="label">买价</span>
                    <span class="text">{{
                      parseInt(futureData && futureData.bidPrice1) || ""
                    }}</span>
                  </li>
                  <li>
                    <span class="label">卖价</span>
                    <span class="text">{{
                      parseInt(futureData && futureData.askPrice1) || ""
                    }}</span>
                  </li>
                </div>
                <div class="flex-between">
                  <li>
                    <span class="label">持仓量</span>
                    <span class="text">{{
                      parseInt(futureData && futureData.openInterest) || ""
                    }}</span>
                  </li>
                  <li>
                    <span class="label">买量</span>
                    <span class="text">{{
                      parseInt(futureData && futureData.bidVolumn1) || ""
                    }}</span>
                  </li>
                  <li>
                    <span class="label">卖量</span>
                    <span class="text">{{
                      parseInt(futureData && futureData.askVolumn1) || ""
                    }}</span>
                  </li>
                </div>
              </ul>
            </div>
          </div>
          <div class="choseGroup">
            <!-- 商品规格选择 -->
            <Sku
              :id="quotationDetailId"
              :quotationDetail="quotationData"
              @getSimilarity="getSimilarity"
              @change="productChange"
              v-if="quotationData.quotationDetailList"
            />
          </div>
          <div class="handle">
            <div
              class="handleItem flex flex-align-c"
              v-if="quotationData.priceType === 1"
            >
              <div class="label">适用合约</div>
              <div class="control contract">
                <c-button type="primary" ghost
                  >{{ quotationData.futuresContract }}
                </c-button>
              </div>
            </div>
            <c-form
              v-model="formHandle"
              ref="formHandle"
              :data="formHandleData"
              :rules="formHandleRules"
              :col="{ labelCol: { style: 'width: 90px;text-align: right;' } }"
            >
              <template v-slot:num>
                <!-- <a-input
                  v-model="formHandle.num"
                  type="number"
                  size="large"
                  style="width: 170px;"
                  step="0.01"
                  min="0"
                  onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                >
                  <a-tooltip slot="suffix">
                    吨
                  </a-tooltip>
                </a-input> -->
                <c-input-number
                  v-model="formHandle.num"
                  :width="170"
                  :fontsize="16"
                >
                  <i slot="suffix">吨</i>
                </c-input-number>
                <span
                  v-if="quotationData.rateLimitType === 0"
                  style="padding-left: 16px;"
                  >下单倍数必须为
                  <i class="danger bold fs-16">{{ quotationData.rateLimit }}</i>
                  的倍数</span
                >
              </template>
              <template v-slot:price>
                <a-input
                  v-model.number="formHandle.price"
                  type="number"
                  size="large"
                  style="width: 170px;"
                >
                  <a-tooltip slot="suffix">
                    元
                  </a-tooltip>
                </a-input>
                <span class="none">{{ getDefaultPricingPrice }}</span>
              </template>
            </c-form>
          </div>
          <Quota
            ref="quota"
            :data="quotationData"
            v-if="quotationData.priceType === 1 && quotationData.id"
          />
          <a-divider dashed />
          <c-button
            type="primary"
            class="submit-btn"
            @click="orders"
            :disabled="
              checkedQuotationProduct.quotationDetailSalesState ===
                quotationDict.detailStatus.sellout.value ||
                companyDirection === companyDict.companyDirection.seller.value
            "
            v-if="$verifyBtn('confirmorder')"
          >
            {{
              quotationData.priceType === quotationDict.priceType.pricing.value
                ? "点价"
                : "下单"
            }}采购
          </c-button>
        </div>
        <div class="divider" />
        <div class="content_r">
          <a-tabs type="card">
            <a-tab-pane key="1" tab="类似商品">
              <Similarity :data="similarityQuotation" />
            </a-tab-pane>
            <a-tab-pane key="2" tab="实物库存明细">
              <Stock
                :productData="checkedQuotationProduct"
                :quotationData="quotationData"
                v-if="quotationData.quotationDetailList"
              />
            </a-tab-pane>
            <a-tab-pane key="3" tab="供应商基本信息">
              <Supplier
                :quotationData="quotationData"
                v-if="quotationData.quotationDetailList"
              />
            </a-tab-pane>
          </a-tabs>
        </div>
      </div>
      <div class="content">
        <ParamsInfo
          :key="quotationData.version"
          :productId="checkedQuotationProduct.id"
          :quotationData="quotationData"
          v-if="quotationData.quotationDetailList"
        />
      </div>
    </a-spin>
    <c-modal
      title="订单确认"
      v-model="orderConfirmVisible"
      :width="400"
      :closeable="false"
      :okLoading="ordersSubmitLoading"
      @ok="ordersSubmit"
    >
      <c-desc :data="orderConfirmForm" :column="1" :columns="orderConfirmDesc">
        <template v-slot:commodity>
          <span>{{ quotationData.categoryName }}</span>
          <a-divider type="vertical" />
          <span>{{ checkedQuotationProduct.brand }} </span>
          <span>{{ checkedQuotationProduct.spec }} </span>
          <span>{{ checkedQuotationProduct.material }} </span>
        </template>
        <template v-slot:price>
          {{ formHandle.price }}
        </template>
        <template v-slot:amount> {{ formHandle.num }} 吨 </template>
      </c-desc>
    </c-modal>
  </div>
</template>

<script>
import TagsDetailStatus from "@/components-business/quotation/detailStatus";
import Similarity from "./components/similarity";
import Sku from "./components/sku";
import ParamsInfo from "./components/paramsInfo";
import Supplier from "./components/supplier";
import Stock from "./components/stock";
import Quota from "./components/quota";
import { getquotationbyid } from "@/api/quotation";
import { confirmorder } from "@/api/order";
import quotationDict from "@/dict/quotation";
import companyDict from "@/dict/company";
import { mapState, mapActions } from "vuex";
import { getPricingPrice } from "@/util/mixins/getPricingPrice";

export default {
  components: {
    Similarity,
    Sku,
    ParamsInfo,
    Supplier,
    Stock,
    Quota,
    TagsDetailStatus
  },
  mixins: [getPricingPrice],
  data() {
    let orderPriceVerify = (rule, value, callback) => {
      if (value <= 0) {
        callback(new Error("请输入价格"));
      }
      callback();
    };
    let orderNumVerify = (rule, value, callback) => {
      if (value <= 0) {
        callback(new Error("请输入数量"));
      }
      callback();
    };
    return {
      once: true, // 是否初始化
      loading: false,
      goodsDescCols: [
        {
          label: "价格",
          slot: "price"
        },
        {
          label: "数量",
          slot: "amount"
        }
      ],
      companyDict,
      quotationDict,
      quotationId: undefined, // 报价id
      quotationDetailId: undefined, // 报价详情id
      quotationData: {}, // 报价信息
      checkedQuotationProduct: {}, // 选择的子商品信息
      similarityQuotation: [], // 相似报价
      ordersSubmitLoading: false, // 下单loading
      orderConfirmVisible: false, // 订单确认弹窗
      orderConfirmForm: {
        companyName: undefined,
        commodity: undefined,
        direction: "采购"
      },
      orderConfirmDesc: [
        {
          label: "公司",
          prop: "companyName"
        },
        {
          label: "商品",
          slot: "commodity"
        },
        {
          label: "方向",
          prop: "direction"
        },
        {
          label: "价格",
          prop: "price",
          slot: "price"
        },
        {
          label: "数量",
          prop: "amount",
          slot: "amount"
        }
      ],
      formHandle: {
        price: 0,
        num: 0
      },
      formHandleRules: {
        price: [{ validator: orderPriceVerify, trigger: "change" }],
        num: [{ validator: orderNumVerify, trigger: "change" }]
      }
    };
  },
  computed: {
    ...mapState(["user", "socketFuture"]),
    // 合约盘面数据
    futureData() {
      let res = this.socketFuture.futureData[
        this.quotationData.futuresContract.toLowerCase()
      ];
      return res;
    },
    formHandleData() {
      let res = [
        {
          label: "数量",
          prop: "num",
          slot: "num"
        },
        {
          label:
            this.quotationData.slidePriceType ===
            this.quotationDict.detailPriceType.base.value
              ? "基价"
              : "含税单价",
          prop: "price",
          slot: "price",
          hidden:
            this.quotationData.priceType !==
            this.quotationDict.priceType.pricing.value
        }
      ];
      return res;
    },
    // 企业身份 1买家 2卖家 3买卖家
    companyDirection() {
      let res = this.user.company && this.user.company.companyDirection;
      return res;
    },
    // 设置默认价格
    getDefaultPricingPrice() {
      let premium =
        this.quotationData.slidePriceType ===
        this.quotationDict.detailPriceType.base.value
          ? 0
          : this.checkedQuotationProduct.premium;
      let price = this.getPricingPrice(
        this.quotationData.futuresContract,
        premium
      );
      return price;
    }
  },
  watch: {
    $route() {
      this.quotationData = {};
      this.init();
    },
    getDefaultPricingPrice(val) {
      // 价格只设置一次，且在大于0时(含税单价点价，要大于升贴水)设置
      if (
        this.quotationData.slidePriceType ===
        this.quotationDict.detailPriceType.base.value
      ) {
        if (this.once && val > 0) {
          this.formHandle.price = val;
          this.once = false;
        }
      } else {
        if (this.once && val > this.checkedQuotationProduct.premium) {
          this.formHandle.price = val;
          this.once = false;
        }
      }
    }
  },
  methods: {
    ...mapActions(["futureWsSend"]),
    // 点击下单
    orders() {
      this.$refs.formHandle.validated().then(() => {
        this.orderConfirmVisible = true;
      });
    },
    // 提交订单
    ordersSubmit() {
      this.ordersSubmitLoading = true;
      confirmorder({
        quotationDetailId: this.checkedQuotationProduct.id,
        amount: Number(this.formHandle.num),
        bid: Number(this.formHandle.price),
        quotation_detail_version: this.checkedQuotationProduct.version
      })
        .then(() => {
          this.init();
          // 如果是点价报价，需更新额度信息
          if (
            this.quotationData.priceType ===
            this.quotationDict.priceType.pricing.value
          )
            this.$refs.quota.queryUsableQuota();
          this.$message.success("下单成功");
          this.orderConfirmVisible = false;
        })
        .finally(() => {
          this.ordersSubmitLoading = false;
        });
    },
    // 选择商品
    productChange(data) {
      this.checkedQuotationProduct = data;
      // 确定价时价格固定，直接赋值
      if (
        this.quotationData.priceType ===
        this.quotationDict.priceType.pricing.value
      ) {
        // // 设置默认价格
        // this.formHandle.price = this.getPricingPrice(
        //   this.quotationData.futuresContract,
        //   this.checkedQuotationProduct.premium
        // );
      } else {
        this.formHandle.price = this.checkedQuotationProduct.price;
      }
    },
    // 获取相似报价
    getSimilarity(data) {
      this.similarityQuotation = data;
    },
    // 获取报价详情
    getQuotationDetail() {
      this.loading = true;
      getquotationbyid({
        quotationId: this.quotationId
      })
        .then(res => {
          if (res.priceType === this.quotationDict.priceType.pricing.value)
            this.futureWsSend([res.futuresContract]);
          this.quotationData = res;
          this.orderConfirmForm.companyName = res.companyName;
          this.orderConfirmForm.commodity = res.categoryName;
          // // 设置价格类型
          // this.formHandleData.forEach(item => {
          //   if (item.prop === "price")
          //     item.label =
          //       this.quotationData.slidePriceType ===
          //       this.quotationDict.detailPriceType.base.value
          //         ? "基价"
          //         : "含税单价";
          // });
          // 更新商品信息
          if (this.checkedQuotationProduct.quotationId) {
            this.quotationData.quotationDetailList.forEach(item => {
              if (this.checkedQuotationProduct.id === item.id) {
                this.checkedQuotationProduct = item;
              }
            });
          }
          // 含税单价点价，需弹窗提示
          if (
            this.quotationData.slidePriceType ===
              this.quotationDict.detailPriceType.tax.value &&
            this.once
          ) {
            let h = this.$createElement;
            this.$info({
              title: "温馨提示",
              content: h("div", {}, [
                h(
                  "p",
                  "注意，此报价采取的是含税单价点价模式，输入的价格为含税单价（结算价），后续若升贴水发生调整，含税单价始终保持不变，而基价相应调整。"
                ),
                h("p", "基价 = 含税单价 -升贴水")
              ])
            });
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    init() {
      let params = this.$route.query;
      if (params.id && params.detailId) {
        this.quotationId = Number(params.id);
        this.quotationDetailId = Number(params.detailId);
        this.getQuotationDetail();
      } else {
        this.$error({
          title: "数据错误，请返回现货商城重新进入"
        });
      }
    }
  },
  created() {
    this.init();
  },
  beforeDestroy() {
    this.$storage.s_remove("spotmallQuotationIds");
  }
};
</script>

<style lang="scss" scoped>
.quotation {
  margin-top: 20px;
  .closingDate {
    padding-left: 40px;
    ::v-deep .ant-alert-message {
      color: var(--warning);
      font-weight: bold;
      font-size: 16px;
    }
  }
  .content {
    padding: 40px;
    margin-bottom: 20px;
    background-color: #fff;
    .content_l {
      flex: 1;
      padding-right: 20px;
      .content_l_head {
        margin-bottom: 16px;
        .goods {
          line-height: 40px;
          font-weight: bold;
          font-size: 16px;
        }
      }
      .goodsData {
        background-color: #fafafa;
        padding: 20px;
        align-items: center;
        .price,
        .weight {
          font-size: 26px;
          font-weight: bold;
          color: var(--danger);
        }
        .weight {
          padding-left: 5px;
        }
        .goodsData_l {
          padding-right: 20px;
          ::v-deep .ant-descriptions-view table {
            table-layout: auto;
          }
          ::v-deep .ant-descriptions-row:last-child .ant-descriptions-item {
            padding-bottom: 0;
          }
        }
        .goodsData_r {
          font-size: 15px;
          border-left: 1px solid #e8e8e8;
          padding-left: 20px;
          width: 50%;
          flex: 1;
          .title {
            margin-bottom: 10px;
            font-weight: bold;
          }
          .market {
            li {
              flex: 1;
              .label::after {
                content: ":";
                position: relative;
                top: -0.5px;
                margin: 0 8px 0 2px;
              }
            }
            div:first-child {
              margin-bottom: 10px;
            }
          }
        }
      }
      .choseGroup {
        margin-top: 24px;
      }
      .handle {
        ::v-deep .ant-form-item-label label {
          font-size: 16px;
        }
        .handleItem {
          margin-bottom: 24px;
          .label {
            flex-shrink: 0;
            font-size: 16px;
            line-height: 40px;
            text-align: right;
            min-width: 90px;
            padding-right: 12px;
          }
          .label::after {
            content: ":";
            position: relative;
            top: -0.5px;
            margin: 0 8px 0 2px;
          }
          .control {
            width: 170px;
          }
          .contract {
            font-size: 16px;
          }
          .rateLimit {
            padding-left: 15px;
          }
        }
      }
      .submit-btn {
        width: 240px;
        height: 40px;
        font-size: 16px;
      }
    }
    .divider {
      width: 1px;
      background-color: #eff2f6;
      margin-right: 20px;
    }
    .content_r {
      flex: 1;
    }
  }
}
</style>
